package com.lambo.maven.core;

import com.lambo.maven.core.utils.IOUtil;
import com.lambo.maven.core.utils.MD5Util;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * sign.
 * Created by lambo on 2018/06/22.
 */
public class SignUtils {
    private static Logger logger = LoggerFactory.getLogger(SignUtils.class);

    public static void signFile(File file) {
        if (null == file|| !file.exists()) {
            return;
        }
        if (file.isFile()) {
            String name = file.getName().toLowerCase();
            if (!name.endsWith(".xml") && !name.endsWith(".jar") && !name.endsWith(".pom")) {
                return;
            }
            try {
                File sha1 = new File(file.getAbsolutePath() + ".sha1");
                File md5 = new File(file.getAbsolutePath() + ".md5");
                if (sha1.exists() && md5.exists()) {
                    return;
                }
                byte[] bytes = IOUtil.readToByteBuffer(file);
                if (!sha1.exists()) {
                    logger.info("create sha1, file = {}", sha1.getAbsolutePath());
                    IOUtil.writeFile(sha1.getAbsolutePath(), MD5Util.sha1Digest(bytes).getBytes());
                }
                if (!md5.exists()) {
                    logger.info("create md5, file = {}", md5.getAbsolutePath());
                    IOUtil.writeFile(md5.getAbsolutePath(), MD5Util.md5Digest(bytes).getBytes());
                }
            } catch (IOException e) {
                logger.error("signFile failed, file = {}", file.getAbsolutePath(), e);
            }
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (File sub : files) {
                    signFile(sub);
                }
            }
        }
    }
}
